#include "irm.h"

static bool irmState;

static void irm_gpio_init(void)
{
    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_GPIOB);
    rcu_periph_clock_enable(RCU_AF);
    gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_11);
    gpio_init(GPIOB, GPIO_MODE_IPU, GPIO_OSPEED_50MHZ, GPIO_PIN_5);
}

static void irm_exit_init(void)
{
    rcu_periph_clock_enable(RCU_AF);
    gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOB, GPIO_PIN_SOURCE_5);
    exti_init(EXTI_5, EXTI_INTERRUPT, EXTI_TRIG_FALLING);
    nvic_irq_enable(EXTI5_9_IRQn, 3, 0);
    exti_interrupt_enable(EXTI_5);
}

static void irm_timer_init(void)
{
    timer_parameter_struct timerInitStruct;
    timer_oc_parameter_struct timerOcStruct;
    
    rcu_periph_clock_enable(RCU_TIMER0);
    timerInitStruct.prescaler = (SystemCoreClock / 4 / 1000000) - 1;
    timerInitStruct.alignedmode = TIMER_COUNTER_EDGE;
    timerInitStruct.counterdirection = TIMER_COUNTER_UP;
    timerInitStruct.period = 2600 - 1;
    timerInitStruct.clockdivision = TIMER_CKDIV_DIV4;
    timerInitStruct.repetitioncounter = 0;
    timer_init(TIMER0, &timerInitStruct);
    timerOcStruct.outputstate = TIMER_CCX_ENABLE;
    timerOcStruct.outputnstate = TIMER_CCXN_DISABLE;
    timerOcStruct.ocpolarity = TIMER_OC_POLARITY_HIGH;
    timerOcStruct.ocnpolarity = TIMER_OCN_POLARITY_HIGH;
    timerOcStruct.ocidlestate = TIMER_OC_IDLE_STATE_LOW;
    timerOcStruct.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW;
    timer_channel_output_config(TIMER0, TIMER_CH_3, &timerOcStruct);

    timer_channel_output_pulse_value_config(TIMER0, TIMER_CH_3, 1300 - 1);
    timer_channel_output_mode_config(TIMER0, TIMER_CH_3, TIMER_OC_MODE_PWM0);
    timer_channel_output_shadow_config(TIMER0, TIMER_CH_3, TIMER_OC_SHADOW_DISABLE);

    timer_auto_reload_shadow_enable(TIMER0);

    timer_enable(TIMER0);
}

void irm_init(void)
{
    irm_gpio_init();
    irm_exit_init();
    irm_timer_init();
}

uint8_t irm_state_get(void)
{
    uint8_t state = irmState;
    irmState = FALSE;
    return state;
}

// void irm_self_test(void)
// {
//     if(irm_state_get())
//     {
//         printf("irm get signal\n");
//     }
// }

void EXTI5_9_IRQHandler(void)
{
    if(exti_interrupt_flag_get(EXTI_5))
    {
        exti_interrupt_flag_clear(EXTI_5);
        irmState = TRUE;
    }
}

